package com.cskaoyan.demo7.controller;

import com.cskaoyan.demo7.bean.model.MarketCart;
import com.cskaoyan.demo7.bean.model.MarketCartExample;
import com.cskaoyan.demo7.bean.resp.CartIndexVo;
import com.cskaoyan.demo7.mapper.MarketCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/23 19:43
 */

@Service("cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    private MarketCartMapper marketCartMapper;
    @Override
    public CartIndexVo index(Integer userId) {
        CartIndexVo cartIndexVo = new CartIndexVo();
        // 查询购物车信息
        List<MarketCart> marketCartList = selectCartListByUserId(userId);
        cartIndexVo.setCartList(marketCartList);
        // 创建CartTotalDTO对象
        CartIndexVo.CartTotalDTO cartTotalDTO = new CartIndexVo.CartTotalDTO();
        // 包装类，创建对象时，默认值都是null
        cartTotalDTO.setCheckedGoodsAmount(BigDecimal.valueOf(0));
        cartTotalDTO.setCheckedGoodsCount(0);
        // 查询购物车中勾选的商品的总价和总件数
        marketCartList.stream().filter(cart -> cart.getChecked() == true).forEach(cart -> {
            cartTotalDTO.setCheckedGoodsAmount(cartTotalDTO.getCheckedGoodsAmount().add(cart.getPrice().multiply(new BigDecimal(cart.getNumber()))));
            cartTotalDTO.setCheckedGoodsCount(cartTotalDTO.getCheckedGoodsCount() + cart.getNumber());
        });


        // 查询购物车中商品的总价和总件数
        cartTotalDTO.setGoodsAmount(BigDecimal.valueOf(0));
        cartTotalDTO.setGoodsCount(0);
        marketCartList.stream().forEach(cart -> {
            cartTotalDTO.setGoodsAmount(cartTotalDTO.getGoodsAmount().add(cart.getPrice().multiply(new BigDecimal(cart.getNumber()))));
            cartTotalDTO.setGoodsCount(cartTotalDTO.getGoodsCount() + cart.getNumber());
        });

        cartIndexVo.setCartTotal(cartTotalDTO);

        return cartIndexVo;
    }

    private List<MarketCart> selectCartListByUserId(Integer userId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria()
                .andDeletedEqualTo(false)
                .andUserIdEqualTo(userId);
        cartExample.setOrderByClause("add_time desc");
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(cartExample);
        return marketCartList;
    }
}
